package day14;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: 王丹
 * @create: 2021-07-06 14:50
 **/
//将本包Demo4代码中的lock.lock()、lock.unlock()去掉，看看会发生什么。
public class Demo5 {
    static ReentrantLock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();

    /**
     * 结果分析：
     * 有异常发生， condition.await();和 condition.signal();都触发了 IllegalMonitorStateException异常。
     * 原因：调用condition中线程等待和唤醒的方法的前提是必须要先获取lock的锁。
     */
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            System.out.println(System.currentTimeMillis() + "," + Thread.currentThread().getName() + " start!");
            try {
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(System.currentTimeMillis() + "," + Thread.currentThread().getName() + " 被唤醒!");
        });
        t1.setName("t1");
        t1.start();
        TimeUnit.SECONDS.sleep(5L);
        condition.signal();

    }

}
